

// 这个类, 负责, 单首歌曲的操作, 播放, 暂停, 停止, 快进, 倍数
import UIKit
import AVFoundation
import FreeStreamer

class singleMusicTool: NSObject {

    var player: AVPlayer?
    var audioStream = FSAudioStream()
    
    var musicState = FSAudioStreamState(rawValue:0)
    
    func playMusic(_ musicName: String?) -> () {
        
        // 1. 创建播放器
        guard let url = Bundle.main.url(forResource: musicName, withExtension: nil) else {return}
        
        player = AVPlayer(url:url)
        
        player?.play()
    }
    
    
    func pauseMusic() -> () {
        player?.pause()
    }
    override init() {
        super.init()
        CLNotificationCenter.addObserver(self, selector: #selector(audioStreamStateDidChange(_:)), name: NSNotification.Name.FSAudioStreamStateChange, object: nil)
    }
    
    /* 初始化网络流媒体对象 */
    func initAudioStream(_ model: musicModel){
        let url = URL(string: model.FileName!)
        self.audioStream = FSAudioStream.init(url: url)
        self.audioStream.play()
    }
    
    func audioStreamStateDidChange(_ notic:Notification){
        
        let dict = (notic as NSNotification).userInfo
        
        let stateNum:Int = (Int)((dict?["state"])! as! NSNumber)
        musicState = FSAudioStreamState(rawValue:stateNum)
        
        if musicState==FSAudioStreamState.fsAudioStreamRetrievingURL {
        } else if musicState==FSAudioStreamState.fsAudioStreamStopped {
            CLNotificationCenter.post(name: Notification.Name(rawValue: "stopPlayAutoNext"), object:nil)
            print("=======停止")
        } else if musicState==FSAudioStreamState.fsAudioStreamBuffering {
            print("=======缓存中")
        } else if musicState==FSAudioStreamState.fsAudioStreamSeeking {
            print("=======定位中")
        } else if musicState==FSAudioStreamState.fsAudioStreamPlaying {
            print("=======播放中")
        } else if musicState==FSAudioStreamState.fsAudioStreamPaused {
            print("=======暂停中")
        } else if musicState==FSAudioStreamState.fsAudioStreamFailed {
            print("=======暂停失败")
        } else if musicState==FSAudioStreamState.fsAudioStreamRetryingStarted {
            print("=======尝试重新播放")
        } else if musicState==FSAudioStreamState.fsAudioStreamEndOfFile {
            print("=======FSAudioStreamEndOfFile")
        }
    }

    
}
